<template>
  <div class="ai-chat-container">
    <!-- 侧边栏 -->
    <div class="chat-sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <el-button 
          type="primary" 
          @click="createNewSession"
          :icon="Plus"
          class="new-chat-btn"
          :disabled="isLoading"
        >
          新对话
        </el-button>
        <el-button 
          text 
          @click="toggleSidebar"
          :icon="sidebarCollapsed ? Expand : Fold"
          class="toggle-btn"
        />
      </div>
      
      <div class="sessions-list" v-show="!sidebarCollapsed">
        <div 
          v-for="session in sessions" 
          :key="session.id"
          class="session-item"
          :class="{ active: currentSessionId === session.id }"
          @click="switchSession(session.id)"
        >
          <div class="session-content">
            <div class="session-title" v-if="!session.editing">{{ session.title }}</div>
            <el-input 
              v-else
              v-model="session.editTitle"
              size="small"
              @blur="saveSessionTitle(session)"
              @keyup.enter="saveSessionTitle(session)"
              ref="titleInput"
            />
            <div class="session-time">{{ formatSessionTime(session.updatedAt) }}</div>
          </div>
          <div class="session-actions">
            <el-button 
              text 
              size="small"
              @click.stop="editSessionTitle(session)"
              :icon="Edit"
            />
            <el-button 
              text 
              size="small"
              @click.stop="deleteSession(session.id)"
              :icon="Delete"
              class="delete-btn"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
        <h2>{{ currentSession?.title || 'AI大模型助手' }}</h2>
        <p>我是MES-DDD的智能对话助手，可以回答您的问题</p>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in currentMessages" :key="index" class="message-item" :class="message.type">
          <div class="message-avatar">
            <el-avatar v-if="message.type === 'user'" :size="32">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="32" style="background-color: #409eff;">
              <el-icon><Service /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="renderMarkdown(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <div v-if="isLoading" class="message-item assistant">
          <div class="message-avatar">
            <el-avatar :size="32" style="background-color: #409eff;">
              <el-icon><ChatDotRound /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <!-- 快捷问题 -->
        <div v-if="currentMessages.length <= 1" class="quick-questions">
          <div class="quick-title">常见问题：</div>
          <div class="quick-buttons">
            <el-button 
              v-for="question in quickQuestions" 
              :key="question"
              size="small" 
              @click="sendQuickQuestion(question)"
              :disabled="isLoading"
            >
              {{ question }}
            </el-button>
          </div>
        </div>
        
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题..."
            @keydown.enter.prevent="handleSend"
            :disabled="isLoading"
            resize="none"
          />
          <div class="input-actions">
            <el-button @click="clearCurrentSession" :disabled="isLoading" text>
              <el-icon><Delete /></el-icon>
              清空对话
            </el-button>
            <el-button type="primary" @click="handleSend" :loading="isLoading" :disabled="!inputMessage.trim()">
              <el-icon><Promotion /></el-icon>
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="AiChat">
import { ref, nextTick, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  User, 
  Service, 
  Delete, 
  Promotion, 
  Plus, 
  Edit, 
  Expand, 
  Fold,
  ChatDotRound 
} from "@element-plus/icons-vue";
import { 
  sendChatMessageStream, 
  createChatSession, 
  getChatSessions, 
  deleteChatSession, 
  updateChatSessionTitle 
} from "@/api/modules/chat";
import { renderMarkdown } from "@/utils/markdown";

interface Message {
  type: 'user' | 'assistant';
  content: string;
  timestamp: Date;
}

interface ChatSession {
  id: string;
  title: string;
  createdAt: Date;
  updatedAt: Date;
  messageCount: number;
  messages: Message[];
  editing?: boolean;
  editTitle?: string;
}

// 响应式数据
const sessions = ref<ChatSession[]>([]);
const currentSessionId = ref<string>('');
const inputMessage = ref("");
const isLoading = ref(false);
const messagesContainer = ref<HTMLElement>();
const sidebarCollapsed = ref(false);

// 快捷问题
const quickQuestions = [
  "你好，请介绍一下自己",
  "什么是MES系统？",
  "如何提高生产效率？",
  "质量管理的重要性",
  "设备维护的最佳实践"
];

// 计算属性
const currentSession = computed(() => 
  sessions.value.find(s => s.id === currentSessionId.value)
);

const currentMessages = computed(() => 
  currentSession.value?.messages || []
);

// 初始化
onMounted(async () => {
  await loadSessions();
  if (sessions.value.length === 0) {
    await createNewSession();
  } else {
    currentSessionId.value = sessions.value[0].id;
  }
});

// 加载会话列表
const loadSessions = async () => {
  try {
    // 这里暂时使用本地存储，后续可以替换为API调用
    const savedSessions = localStorage.getItem('chatSessions');
    if (savedSessions) {
      const parsedSessions = JSON.parse(savedSessions);
      sessions.value = parsedSessions.map((s: any) => ({
        ...s,
        createdAt: new Date(s.createdAt),
        updatedAt: new Date(s.updatedAt),
        messages: s.messages.map((m: any) => ({
          ...m,
          timestamp: new Date(m.timestamp)
        }))
      }));
    }
  } catch (error) {
    console.error('加载会话失败:', error);
  }
};

// 保存会话到本地存储
const saveSessions = () => {
  localStorage.setItem('chatSessions', JSON.stringify(sessions.value));
};

// 创建新会话
const createNewSession = async () => {
  const newSession: ChatSession = {
    id: generateSessionId(),
    title: '新对话',
    createdAt: new Date(),
    updatedAt: new Date(),
    messageCount: 0,
    messages: [{
      type: 'assistant',
      content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？',
      timestamp: new Date()
    }]
  };
  
  sessions.value.unshift(newSession);
  currentSessionId.value = newSession.id;
  saveSessions();
};

// 生成会话ID
const generateSessionId = () => {
  return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// 切换会话
const switchSession = (sessionId: string) => {
  currentSessionId.value = sessionId;
  nextTick(() => {
    scrollToBottom();
  });
};

// 删除会话
const deleteSession = async (sessionId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '确认删除', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    sessions.value = sessions.value.filter(s => s.id !== sessionId);
    
    if (currentSessionId.value === sessionId) {
      if (sessions.value.length > 0) {
        currentSessionId.value = sessions.value[0].id;
      } else {
        await createNewSession();
      }
    }
    
    saveSessions();
    ElMessage.success('对话已删除');
  } catch {
    // 用户取消删除
  }
};

// 编辑会话标题
const editSessionTitle = (session: ChatSession) => {
  session.editing = true;
  session.editTitle = session.title;
};

// 保存会话标题
const saveSessionTitle = (session: ChatSession) => {
  if (session.editTitle && session.editTitle.trim()) {
    session.title = session.editTitle.trim();
    session.updatedAt = new Date();
    saveSessions();
  }
  session.editing = false;
  delete session.editTitle;
};

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
};

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;
  
  const userMessage = inputMessage.value.trim();
  const session = currentSession.value;
  if (!session) return;
  
  // 添加用户消息
  session.messages.push({
    type: 'user',
    content: userMessage,
    timestamp: new Date()
  });
  
  // 更新会话标题（如果是第一条用户消息）
  if (session.messageCount === 0) {
    session.title = userMessage.length > 20 ? userMessage.substring(0, 20) + '...' : userMessage;
  }
  
  session.messageCount++;
  session.updatedAt = new Date();
  
  inputMessage.value = "";
  isLoading.value = true;
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 添加一个空的AI消息，用于流式更新
  const aiMessageIndex = session.messages.length;
  session.messages.push({
    type: 'assistant',
    content: '',
    timestamp: new Date()
  });
  
  try {
    sendChatMessageStream(
      { 
        message: userMessage,
        memoryId: session.id 
      },
      // onMessage - 处理每个数据块
      (chunk: string) => {
        // 累积内容到AI消息中
        session.messages[aiMessageIndex].content += chunk;
        scrollToBottom();
      },
      // onComplete - 流结束
      () => {
        isLoading.value = false;
        // 如果没有收到任何内容，显示默认消息
        if (!session.messages[aiMessageIndex].content.trim()) {
          session.messages[aiMessageIndex].content = '抱歉，我暂时无法回答这个问题。';
        }
        session.updatedAt = new Date();
        saveSessions();
        scrollToBottom();
      },
      // onError - 错误处理
      (error: any) => {
        console.error('Chat error:', error);
        
        let errorMessage = '抱歉，服务暂时不可用，请稍后重试。';
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error?.message) {
          errorMessage = `连接失败: ${error.message}`;
        }
        
        ElMessage.error('发送消息失败，请稍后重试');
        
        // 更新AI消息为错误消息
        session.messages[aiMessageIndex].content = errorMessage;
        isLoading.value = false;
        saveSessions();
        scrollToBottom();
      }
    );
    
  } catch (error: any) {
    console.error('Chat error:', error);
    ElMessage.error('发送消息失败，请稍后重试');
    
    session.messages[aiMessageIndex].content = '抱歉，服务暂时不可用，请稍后重试。';
    isLoading.value = false;
    saveSessions();
    scrollToBottom();
  }
};

// 清空当前会话
const clearCurrentSession = async () => {
  try {
    await ElMessageBox.confirm('确定要清空当前对话吗？', '确认清空', {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const session = currentSession.value;
    if (session) {
      session.messages = [{
        type: 'assistant',
        content: '对话已清空。有什么新的问题需要帮助吗？',
        timestamp: new Date()
      }];
      session.messageCount = 0;
      session.updatedAt = new Date();
      saveSessions();
    }
  } catch {
    // 用户取消清空
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 格式化时间
const formatTime = (timestamp: Date) => {
  return timestamp.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

// 格式化会话时间
const formatSessionTime = (timestamp: Date) => {
  const now = new Date();
  const diff = now.getTime() - timestamp.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    return timestamp.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return timestamp.toLocaleDateString('zh-CN');
  }
};

// 发送快捷问题
const sendQuickQuestion = (question: string) => {
  inputMessage.value = question;
  handleSend();
};
</script>
<style scop
ed lang="scss">
.ai-chat-container {
  height: calc(100vh - 120px);
  display: flex;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.chat-sidebar {
  width: 280px;
  background: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  
  &.collapsed {
    width: 60px;
    
    .new-chat-btn span {
      display: none;
    }
  }
  
  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    align-items: center;
    gap: 8px;
    
    .new-chat-btn {
      flex: 1;
      justify-content: flex-start;
    }
    
    .toggle-btn {
      flex-shrink: 0;
    }
  }
  
  .sessions-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    
    .session-item {
      padding: 12px;
      margin-bottom: 4px;
      border-radius: 8px;
      cursor: pointer;
      transition: background-color 0.2s;
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      &:hover {
        background: #e9ecef;
        
        .session-actions {
          opacity: 1;
        }
      }
      
      &.active {
        background: #409eff;
        color: white;
        
        .session-time {
          color: rgba(255, 255, 255, 0.8);
        }
      }
      
      .session-content {
        flex: 1;
        min-width: 0;
        
        .session-title {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .session-time {
          font-size: 12px;
          color: #999;
        }
      }
      
      .session-actions {
        opacity: 0;
        transition: opacity 0.2s;
        display: flex;
        gap: 4px;
        
        .delete-btn:hover {
          color: #f56c6c;
        }
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .chat-header {
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    text-align: center;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
    }
    
    p {
      margin: 0;
      opacity: 0.9;
      font-size: 14px;
    }
  }
  
  .chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f8f9fa;
    
    .message-item {
      display: flex;
      margin-bottom: 20px;
      
      &.user {
        flex-direction: row-reverse;
        
        .message-content {
          margin-right: 12px;
          margin-left: 0;
          
          .message-text {
            background: #409eff;
            color: white;
          }
        }
      }
      
      &.assistant {
        .message-content {
          margin-left: 12px;
          
          .message-text {
            background: white;
            color: #333;
            border: 1px solid #e4e7ed;
          }
        }
      }
    }
    
    .message-avatar {
      flex-shrink: 0;
    }
    
    .message-content {
      max-width: 70%;
      
      .message-text {
        padding: 12px 16px;
        border-radius: 12px;
        line-height: 1.5;
        word-wrap: break-word;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        
        // Markdown 样式
        :deep(.inline-code) {
          background: rgba(0, 0, 0, 0.1);
          padding: 2px 4px;
          border-radius: 3px;
          font-family: 'Courier New', monospace;
          font-size: 0.9em;
          color: #e83e8c;
        }
        
        :deep(pre.hljs) {
          background: #f8f9fa;
          padding: 12px;
          border-radius: 6px;
          overflow-x: auto;
          margin: 8px 0;
          border: 1px solid #e9ecef;
          
          code {
            background: none;
            padding: 0;
            font-family: 'Courier New', 'Monaco', monospace;
            font-size: 0.9em;
          }
        }
        
        :deep(blockquote) {
          border-left: 4px solid #409eff;
          margin: 8px 0;
          padding: 8px 16px;
          background: #f8f9fa;
          color: #666;
          font-style: italic;
        }
        
        :deep(.markdown-table) {
          width: 100%;
          border-collapse: collapse;
          margin: 8px 0;
          
          th, td {
            border: 1px solid #ddd;
            padding: 8px 12px;
            text-align: left;
          }
          
          th {
            background: #f5f5f5;
            font-weight: 600;
          }
          
          tr:nth-child(even) {
            background: #f9f9f9;
          }
        }
        
        :deep(ul, ol) {
          margin: 8px 0;
          padding-left: 20px;
          
          li {
            margin: 4px 0;
          }
        }
        
        :deep(h1, h2, h3, h4, h5, h6) {
          margin: 16px 0 8px 0;
          font-weight: 600;
          line-height: 1.2;
        }
        
        :deep(h1) { font-size: 1.5em; }
        :deep(h2) { font-size: 1.3em; }
        :deep(h3) { font-size: 1.1em; }
        
        :deep(p) {
          margin: 8px 0;
          line-height: 1.6;
        }
        
        :deep(a) {
          color: #409eff;
          text-decoration: none;
          
          &:hover {
            text-decoration: underline;
          }
        }
        
        :deep(strong) {
          font-weight: 600;
        }
        
        :deep(em) {
          font-style: italic;
        }
        
        :deep(hr) {
          border: none;
          border-top: 1px solid #eee;
          margin: 16px 0;
        }
      }
      
      .message-time {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
        text-align: center;
      }
    }
  }
  
  .typing-indicator {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 12px;
    
    span {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #409eff;
      margin-right: 4px;
      animation: typing 1.4s infinite ease-in-out;
      
      &:nth-child(1) { animation-delay: -0.32s; }
      &:nth-child(2) { animation-delay: -0.16s; }
      &:nth-child(3) { 
        margin-right: 0;
        animation-delay: 0s; 
      }
    }
  }
  
  .chat-input {
    padding: 20px;
    background: white;
    border-top: 1px solid #e4e7ed;
    
    .quick-questions {
      margin-bottom: 16px;
      
      .quick-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }
      
      .quick-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-button {
          border-radius: 16px;
          font-size: 12px;
          padding: 6px 12px;
        }
      }
    }
    
    .input-container {
      .input-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12px;
      }
    }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

// 滚动条样式
.sessions-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.sessions-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.sessions-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  
  &:hover {
    background: #a8a8a8;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .ai-chat-container {
    .chat-sidebar {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      z-index: 1000;
      transform: translateX(-100%);
      transition: transform 0.3s ease;
      
      &:not(.collapsed) {
        transform: translateX(0);
      }
    }
    
    .chat-main {
      width: 100%;
    }
  }
}
</style>